package org.ntu.csn.as.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Session;
import org.ntu.csn.as.manager.DBManager;
import org.ntu.csn.as.model.SysMessage;
import org.ntu.csn.as.model.Userinfo;
import org.ntu.csn.as.tool.Constant;
import org.ntu.csn.as.tool.MD5Util;

/**
 * Servlet implementation class LoginController
 */
@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Login Controller.....");
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		String encodedPwd = MD5Util.md5(pwd);
		Userinfo userinfo = new Userinfo();
		userinfo.setName(name);
		userinfo.setPwd(encodedPwd);

		DBManager dbm = new DBManager();
		try {
			if (dbm.isUserAndPwdValid(userinfo)) {
				HttpSession session = request.getSession();
				session.setAttribute("userinfo", userinfo);
				System.out.println("Login User:" + userinfo.getName() + " Pwd:"
						+ userinfo.getPwd());
				request.getRequestDispatcher("index.jsp").forward(request,
						response);

			} else {

				SysMessage message = new SysMessage();
				message.setType(Constant.MESSAGE_ERROR);
				message.setMessage("Invalid UserName or Password");
				message.setSourceURL("login.jsp");
				request.setAttribute("errorMsg", message);
				request.getRequestDispatcher(message.getSourceURL()).forward(
						request, response);

			}
		
		} catch (Exception e) {
			SysMessage message = new SysMessage();
			message.setType(Constant.MESSAGE_ERROR);
			message.setMessage("Invalid UserName or Password");
			message.setSourceURL("login.jsp");
			request.setAttribute("errorMsg", message);
			request.getRequestDispatcher(message.getSourceURL()).forward(
					request, response);

		}

	}

}
